package com.iwinding.ladygg.ui.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.util.EasyUtils;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.constant.EMConstant;
import com.iwinding.ladygg.modle.bean.EMSosMessageBean;
import com.iwinding.ladygg.ui.act.AddFriendActivity;
import com.iwinding.ladygg.ui.act.ChatRoomDetailsActivity;
import com.iwinding.ladygg.ui.act.GroupDetailsActivity;
import com.iwinding.ladygg.ui.view.ChatRowSosCall;

import java.util.Map;

/**
 * Created by hezhiyong on 2017/4/8.
 */

public class ChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentHelper {

    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;


    private static final int REQUEST_CODE_GROUP_DETAIL = 13;

    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 1;
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 2;
    private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 3;
    private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 4;
    private static final int MESSAGE_TYPE_SENT_SOS = 5;
    private static final int MESSAGE_TYPE_RECV_SOS = 6;

    @Override
    protected void setUpView() {
        setChatFragmentListener(this);
        super.setUpView();
        // set click listener
        titleBar.setRightLayoutVisibility(View.GONE);
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (EasyUtils.isSingleActivity(getActivity())) {
                    Intent intent = new Intent(getActivity(), AddFriendActivity.class);
                    startActivity(intent);
                }
                onBackPressed();
            }
        });
//        if(chatType == EaseConstant.CHATTYPE_GROUP){
//            inputMenu.getPrimaryMenu().getEditText().addTextChangedListener(new TextWatcher() {
//
//                @Override
//                public void onTextChanged(CharSequence s, int start, int before, int count) {
//                    if(count == 1 && "@".equals(String.valueOf(s.charAt(start)))){
//                        startActivityForResult(new Intent(getActivity(), PickAtUserActivity.class).
//                                putExtra("groupId", toChatUsername), REQUEST_CODE_SELECT_AT_USER);
//                    }
//                }
//                @Override
//                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//                }
//                @Override
//                public void afterTextChanged(Editable s) {
//
//                }
//            });
//        }
    }

    @Override
    protected void registerExtendMenuItem() {
        //use the menu in base class
        super.registerExtendMenuItem();
        //extend menu items
//        if (chatType == EMConstant.CHATTYPE_SINGLE) {
//            inputMenu.registerExtendMenuItem(R.string.attach_voice_call, R.drawable.em_chat_voice_call_selector, ITEM_VOICE_CALL, extendMenuItemClickListener);
//            inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.drawable.em_chat_video_call_selector, ITEM_VIDEO_CALL, extendMenuItemClickListener);
//        }
    }


    /**
     * 设置消息扩展属性
     */
    @Override
    public void onSetMessageAttributes(EMMessage message) {
    }

    /**
     * 进入会话管理详情
     */
    @Override
    public void onEnterToChatDetails() {
        //群管理界面
        if (chatType == EMConstant.CHATTYPE_GROUP) {
            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
            if (group == null) {
                Toast.makeText(getActivity(), R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
                return;
            }
            startActivityForResult(
                    (new Intent(getActivity(), GroupDetailsActivity.class).putExtra("groupId", toChatUsername)),
                    REQUEST_CODE_GROUP_DETAIL);
        } else if (chatType == EMConstant.CHATTYPE_CHATROOM) {
            startActivityForResult(new Intent(getActivity(), ChatRoomDetailsActivity.class).putExtra("roomId", toChatUsername), REQUEST_CODE_GROUP_DETAIL);
        }
    }

    /**
     * 用户头像点击事件
     *
     * @param username
     */
    @Override
    public void onAvatarClick(String username) {

    }

    /**
     * 用户头像长按事件
     *
     * @param username
     */
    @Override
    public void onAvatarLongClick(String username) {

    }

    /**
     * 消息气泡框点击事件
     */
    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
//        if (message.getType() == EMMessage.Type.TXT) {
//            EMTextMessageBody body = (EMTextMessageBody) message.getBody();
//            String msg = body.getMessage();
//            ToastUtil.openBaseToast(getActivity(), msg, Toast.LENGTH_SHORT);
//        }
        return false;
    }

    /**
     * 消息气泡框长按事件
     */
    @Override
    public void onMessageBubbleLongClick(EMMessage message) {

    }

    /**
     * 扩展输入栏item点击事件,如果要覆盖EaseChatFragment已有的点击事件，return true
     *
     * @param view
     * @param itemId
     * @return
     */
    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
//        switch (itemId) {
//            case ITEM_VOICE_CALL:
//                startVoiceCall();
//                break;
//            case ITEM_VIDEO_CALL:
//                startVideoCall();
//                break;
//            //end of red packet code
//            default:
//                break;
//        }
        //keep exist extend menu
        return false;
    }

    /**
     * 设置自定义chatrow提供者
     *
     * @return
     */
    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        return new CustomChatRowProvider();
    }

    /**
     * make a voice call
     */
    protected void startVoiceCall() {
//        if (!EMClient.getInstance().isConnected()) {
//            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
//        } else {
//            startActivity(new Intent(getActivity(), VoiceCallActivity.class).putExtra("username", toChatUsername)
//                    .putExtra("isComingCall", false));
//            // voiceCallBtn.setEnabled(false);
//            inputMenu.hideExtendMenuContainer();
//        }
    }

    /**
     * make a video call
     */
    protected void startVideoCall() {
//        if (!EMClient.getInstance().isConnected())
//            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
//        else {
//            startActivity(new Intent(getActivity(), VideoCallActivity.class).putExtra("username", toChatUsername)
//                    .putExtra("isComingCall", false));
//            // videoCallBtn.setEnabled(false);
//            inputMenu.hideExtendMenuContainer();
//        }
    }

    /**
     * chat row provider
     */
    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //here the number is the message type in EMMessage::Type
            //which is used to count the number of different chat row
            return 12;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if (message.getType() == EMMessage.Type.TXT) {
                //voice call
                Map<String, Object> exts = message.ext();
                if (exts != null && exts.size() != 0) {
                    String type = convertStr(exts.get(EMSosMessageBean.Attribute.VALUES[0]));
                    if (!TextUtils.isEmpty(type)) {
                        return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_SOS : MESSAGE_TYPE_SENT_SOS;
                    }
                }
//                if (message.getBooleanAttribute(EMConstant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
//                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL : MESSAGE_TYPE_SENT_VOICE_CALL;
//                } else if (message.getBooleanAttribute(EMConstant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
//                    //video call
//                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
//                }
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if (message.getType() == EMMessage.Type.TXT) {
                // voice call or video call
//                if (message.getBooleanAttribute(EMConstant.MESSAGE_ATTR_IS_VOICE_CALL, false) ||
//                        message.getBooleanAttribute(EMConstant.MESSAGE_ATTR_IS_VIDEO_CALL, false)){
//                    return new ChatRowVoiceCall(getActivity(), message, position, adapter);
//                }
                Map<String, Object> exts = message.ext();
                if (exts != null && exts.size() != 0) {
                    String type = convertStr(exts.get(EMSosMessageBean.Attribute.VALUES[0]));
                    if (!TextUtils.isEmpty(type)) {
                        return new ChatRowSosCall(getActivity(), message, position, adapter);
                    }
                }
            }
            return null;
        }
    }

    /**
     * 转换成Str
     * @param object
     * @return
     */
    private String convertStr(Object object) {
        if (object instanceof String)
            return (String) object;
        if (object == null) {
            return null;
        }
        return String.valueOf(object);
    }


}
